﻿using GymTimer.Models;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GymTimer.Data
{
    public  class TimerDataBase
    {
        private bool inited = false;
        private readonly SQLiteAsyncConnection Database;
        public TimerDataBase() {

            Database = new SQLiteAsyncConnection(Constants.TimerDatabasePath, Constants.Flags);


        }


        async Task Init()
        {
            if (inited)
            {
                return;
            }

            string path1 = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string path=FileSystem.AppDataDirectory;
            if(!Directory.Exists(path1))
            {
                Directory.CreateDirectory(path);
                Directory.CreateDirectory(path1);
            }



            //Database = new SQLiteAsyncConnection(Constants.TimerDatabasePath, Constants.Flags);




            var result =await Database.CreateTableAsync<Schedule>();
            result=await Database.CreateTableAsync<Exercise>();

            inited = true;

        }

        public async Task<List<Schedule>>  GetSchedulesAsync()
        {
            await Init();
            return await Database.Table<Schedule>().ToListAsync();
        }

        public async Task<Schedule>  GetScheduleAsync(int id)
        {
            await Init();
            return await Database.Table<Schedule>().Where(i=>i.ID==id).FirstOrDefaultAsync();
        }


        public async Task<List<Exercise>> GetExerciseAsync(int scheduleId)
        {
            await Init();
            return await Database.Table<Exercise>().Where(i => i.ScheduleID == scheduleId).ToListAsync();
        }


        public async Task<int> SaveExercise(Exercise e)
        {
            await Init();
            if (e.ID != 0)
            {
                return await Database.UpdateAsync(e);

            }
            else
            {
                return await Database.InsertAsync(e);
            }

        }


        public async Task<int> SaveSchedule(Schedule schedule)
        {
            await Init();
            if(schedule.ID!=0)
            {
                return await Database.UpdateAsync(schedule);

            }else
            {
                return await  Database.InsertAsync(schedule);
            }

        }

        public async Task<int> DeleteSchedule(Schedule schedule)
        {
            await Init();
            return await Database.DeleteAsync(schedule);
        }

        public async Task<int> DeleteExercise(Exercise e)
        {
            await Init();
            return await Database.DeleteAsync(e);
        }



    }
}
